<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<!DOCTYPE html>
<html lang="zh-CN">
    <head> 
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <%@ include file="/WEB-INF/views/include/head.jsp"%>
    <link rel="stylesheet" href="${ctxStatic}/css/common_erp.css">
    <link rel="stylesheet" href="${ctxStatic}/css/layerSm.css">
    <script src="${ctxStatic}/js/jquery-1.9.1.min.js"></script>
    <script src="${ctxStatic}/js/DateTimePicker.js"></script>
    <script src="${ctxStatic}/js/layer.js"></script>
    <script src="${ctxStatic}/js/style.js"></script>
    <script src="${ctxStatic}/layDate/laydate.js"></script>
    <script>

  // tab页切换方法
	$(function() {
		$(".tabBox ul li").each(
			function() {
			var index = $(this).index();
			$(".tabBox ul li").eq(0).addClass("active");
			$(this).click(function() {
				$(this).addClass("active").siblings()
						.removeClass("active");
				$(".tabBoxSm > .tabSm").eq(index).stop(true)
						.show().siblings().stop(true).hide();
				//btnCheck(index);
				//inputData();
				var tableW = $(".tabBoxSm > .tabSm").eq(index)
						.find('.tableHead').width();
				var tabodyH = $(".tabBoxSm > .tabSm").eq(index)
						.find('.tableBody').height();
				var tableScrollH = $(".tabBoxSm > .tabSm").eq(
						index).find('.tableScroll').height();
				if (tabodyH > tableScrollH) {
					$(".tabBoxSm > .tabSm").eq(index).find(
							'.tableScroll').css('width',
							tableW + 18 + 'px')
				} else {
					$(".tabBoxSm > .tabSm").eq(index).find(
							'.tableScroll').css('width',
							'inherit')
				}
			})
		})
	})

  $(document).ready(function(){ 
	 
	  		findUnitTwo(${bigConsumption.id});
	  		var form = $("#inputForm");  
   			form.validate();//验证指定的表单
       		unitFun(${bigConsumption.styleId},"unitCostNo");             
       		$("#confirmBtn").click(function(){
        		if (form.valid()) {//如果表单验证成功，则进行提交。  
        		$("#showHtml").addClass("showHtml");
                $("#confirmPage").css("display","block");
                $("#editPage").css("display","none");
                $("input").attr("readOnly","readOnly");
                $("select").attr("disabled","disabled");
                return false;
              	}
         	});
        }); 
	
    /* 删除 面料  */
 	function removeFun(obj){  
		 if (confirm("<spring:message code="quotation_create_areYouSure"/>")) {
            var tr=obj.parentNode.parentNode;  
            var tbody=tr.parentNode 
            tbody.removeChild(tr); 
		}
	 }

	// 面辅配料画面回调方法
	function realoadFun() {
 	//给这些单元格注册鼠标点击事件  
	$("#listHtml").find("td[class^='tabInput-']").on("click",function(){
	        //找到当前鼠标单击的td
	        var tdObj = $(this);
	        //保存原来的文本  
	        var oldText = $(this).text();
			var tempName = $(this)[0].id;
			
	        //创建一个文本框  
	        var inputObj = $("<textarea id='materialRemarks' name='materialRemarks' value='"+oldText+"'>"+oldText+"</textarea>");
	        var index = $(this).parent().index();
	        //去掉文本框的边框  
	        inputObj.css("border-width", 0);
	        inputObj.click(function () {
	            return false;
	        });
	        //使文本框的宽度和td的宽度相同  
	        inputObj.width(tdObj.width());
	        inputObj.height(tdObj.height());
	        //去掉文本框的外边距 
	        inputObj.css("margin", 0);
	        inputObj.css("padding", 0);
	        //把文本框放到td中  
	        tdObj.html(inputObj);
	        //文本框失去焦点的时候变为文本  
	        inputObj.blur(function () {
	            var newText = $(this).val();
	            $("#listHtml tr").eq(index).find("."+tempName).val(newText);
	            tdObj.html(newText);
	            
	            //addstart
                var $objTr = $("#listHtml tr").eq(index);
	            var $allConsumption = (parseFloat($objTr.find("td").eq(6).text().replace(/,/,""))).toFixed(6) * (1+(parseFloat($objTr.find("td").eq(7).text().replace(/,/,""))/100));
	            $objTr.find("td").eq(8).text($allConsumption);
	            var $allPrice=parseFloat($objTr.find("td").eq(8).text().replace(/,/,"")) * parseFloat($objTr.find("td").eq(9).text().replace(/,/,""));
	            $objTr.find("td").eq(10).text($allPrice);
	            formatMoneyThis($objTr.find("td").eq(6), 2);
	            formatMoneyThis($objTr.find("td").eq(7), 2);
	            formatMoneyThis($objTr.find("td").eq(8), 2);
	            formatMoneyThis($objTr.find("td").eq(9), 2);
	            formatMoneyThis($objTr.find("td").eq(10), 2);
	            $("#listHtml tr").eq(index).find(".materialTotalPrice").val($allPrice);
	            $("#listHtml tr").eq(index).find(".materialLoss").val($allConsumption);
	            //addend
	           
	        });
	        //全选  
	        inputObj.trigger("focus").trigger("select");
	    });

	}
	//格式化金额
    function formatMoneyThis(e, n) {  
    	var s=$(e).text().replace(",","").trim();
    	//判断字符串是否为数字     //判断正整数 /^[1-9]+[0-9]*]*$/  
    	var numberVerification = /^[0-9]+.?[0-9]*$/;   
        if (numberVerification.test(s)){
        	n = n > 0 && n <= 20 ? n : 2;  
            s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";  
            var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];  
            t = "";  
            for (var i = 0; i < l.length; i++) {  
                t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
            } 
            $(e).text(t.split("").reverse().join("") + "." + r);
        }else{
        	$(e).text("");
        }
    }  
    
  //单耗联动
     function unitFun(t,id){
        var code=t;
        var param={"code":code};
         $.post("${ctx}/bigcargo/consumption/unitCost",param,function(result){
            var html="<option value=''><spring:message code="company_edit_pleaseChoose"/></option>";
            var costID = ""/* ${bigConsumption.id} */;
            $.each(result,function(i,e){
                html+="<option value='"+e.id+"'";
                if (costID==e.id) {
					html+="selected='selected'";
				}
                html+=" >"+e.unitCostNo+"</option>";
            });
            $("#"+id).html(html);
            $("#"+id).select2();
        },'json'); 
    } 
  
     function findMaterial(){
    	 var code = $("#styleId").val();
     	var param={"code":code};
     	$.post("${ctx}/bigcargo/consumption/findMaterial",param,function(result){
     		var listHtml = result["materialList"];
			$("#listHtml").html(listHtml);
			realoadFun();
     	},'json');
     }
    // 根据单耗联动返回中间规格、损耗率、参考成本、备注 联动返回面辅配料
    function findUnit(t){
    	var code = $(t).find("option:selected").attr("value");
    	var param={"code":code};
    	if(code!=null && code!=""){
    	$.post("${ctx}/bigcargo/consumption/material",param,function(result){
			var listHtml = result["materialList"];
			var unitCostLossRate = result["unitCostLossRate"];
			var unitCostMiddleStandard = result["unitCostMiddleStandard"];
			var unitCost = result["unitCost"];
			var unitCostRemark = result["unitCostRemark"];
			$("#listHtml").html(listHtml);
			$("#unitCostLossRate").val(unitCostLossRate);
			$("#unitCostMiddleStandard").val(unitCostMiddleStandard);
			$("#unitCost").val(unitCost);
			$("#unitCostRemark").val(unitCostRemark);
		
			realoadFun();
    	},'json');
    	}
    }
    
    function findUnitTwo(t){
    	var code = t;
    	var param={"code":code};
    	if(code!=null && code!=""){
    	$.post("${ctx}/bigcargo/consumption/material",param,function(result){
			var listHtml = result["materialList"];
			$("#listHtml").html(listHtml);
			realoadFun();
    	},'json');
    	
    	}
    }
    
    /* 保存创建/编辑信息 */
    function saveForm(){
    	$("select").removeAttr("disabled");
    	formUnFormat($("#inputForm"));
    	var params = $("#inputForm").serialize();
    	$.post("${ctx}/bigcargo/consumption/save",params,function(result){
    		/* 弹出提示框,刷新父页面,关闭当前页面 */
    		tipParent(result.message);
    		 window.parent.frames[0].searchListForm();
    		closeWin();
    	},'json');
    	
    }
    
    // 选择物料回调
    function selectMaterialCallBack(selectIndex,objMaterials){
    	if(selectIndex==null || selectIndex==''){
    		return;
    	}
    	
    	var tbodyTemp = $("#listHtml");
    	var len = $(tbodyTemp).find("tr").length-1;
    	
    	// 分割选择id
    	strSelects = selectIndex.split(",");
    	for (i=0;i<objMaterials.length ;i++ ){
    		 for(j=0;j<strSelects.length;j++){
    			  var idx = parseInt(strSelects[j]);
                  if(i==idx){
              		var materialCode = objMaterials[i].materialCode;
            		var materialCodeHidden = "<input type='hidden' class = '' name='bigConsumption.bigConsumptionMaterialList["+(i+len)+"].materialCode' value='"+materialCode+"'/>"; 
            		var materialNameCN = objMaterials[i].materialNameCn;
            		var materialNameCNHidden = "<input type='hidden' name='bigConsumption.bigConsumptionMaterialList["+(i+len)+"].materialNameCN' value='"+materialNameCN+"'/>";
            		var materialTypeCd = objMaterials[i].materialTypeCn;
            		var materialTypeCdHidden = "<input type='hidden' name='bigConsumption.bigConsumptionMaterialList["+(i+len)+"].materialTypeCd' value='"+materialTypeCd+"'/>";
					var materialSpec = objMaterials[i].materialSpec;
            		var materialSpecHidden = "<input type='hidden' name='bigConsumption.bigConsumptionMaterialList["+(i+len)+"].materialSpec' value='"+materialSpec+"'/>";
            		var materialCostHidden = "<input type ='hidden' class = 'materialCost' name ='bigConsumptionMaterialList["+(i+len)+"].materialCost' />"
            		var materialPreLossHidden = "<input type ='hidden' class = 'materialPreLoss' name ='bigConsumptionMaterialList["+(i+len)+"].materialPreLoss' />"
            		var materialLossHidden = "<input type ='hidden' class = 'materialLoss' name ='bigConsumptionMaterialList["+(i+len)+"].materialLoss' />"
            		var materialUnitPriceHidden = "<input type ='hidden' class = 'materialUnitPrice' name ='bigConsumptionMaterialList["+(i+len)+"].materialUnitPrice' />"
            		var materialTotalPriceHidden = "<input type ='hidden' class = 'materialTotalPrice' name ='bigConsumptionMaterialList["+(i+len)+"].materialTotalPrice' />"
            		var remarksHidden = "<input type ='hidden' class = 'remarks' name ='bigConsumptionMaterialList["+(i+len)+"].remarks' />"
            		var materialId = objMaterials[i].materialId;
            		var materialIDHidden = "<input type='hidden' class = 'materialID' name='bigConsumptionMaterialList["+(i+len)+"].materialID' value='"+materialId+"'/>"; 
            		var tempDataHidden = materialCodeHidden+materialNameCNHidden+materialTypeCdHidden+materialSpecHidden
            							+materialCostHidden+materialPreLossHidden+materialLossHidden+materialUnitPriceHidden
            							+materialTotalPriceHidden+remarksHidden+materialIDHidden;
            		var mfileTemp = objMaterials[i].fileName;
            		var tempData = $(tbodyTemp).find("tr").eq(0).clone();
            		var tempDataCells=$(tempData)[0].cells;
            		tempDataCells[1].innerHTML="<img src='"+mfileTemp+"' class='wltp'>";
            		tempDataCells[2].innerHTML=materialCode+"<br>" + materialNameCN;
            		tempDataCells[3].innerText=materialTypeCd;
            		tempDataCells[4].innerText=materialSpec;
            		tempDataCells[5].innerText=objMaterials[i].materialUnitCn;
            		
            		tempDataCells[12].innerHTML=tempDataHidden;
            		
            		$(tempData)[0].className="";
            		tempData.appendTo(tbodyTemp);
                  }    			 
    		 }
    	}
    	realoadFun();
    }
    function giveThisData() {
		var unitCostLossRate = $("#unitCostLossRate").val();
		var trLgh = $("#listHtml tr").length;
		var $cld;
		for (var i = 0; i < trLgh; i++) {
			$cld = $("#listHtml tr").eq(i);
			$cld.find("td").eq(7).text(unitCostLossRate);
			$cld.find(".materialPreLoss").val(unitCostLossRate);
			childFunc(i);
		}
	}
    function childFunc(index) {
    	var $objTr = $("#listHtml tr").eq(index);
        var $allConsumption = (parseFloat($objTr.find("td").eq(6).text().replace(/,/,""))).toFixed(6) * (1+(parseFloat($objTr.find("td").eq(7).text().replace(/,/,""))/100));
        $objTr.find("td").eq(8).text($allConsumption);
        var $allPrice=parseFloat($objTr.find("td").eq(8).text().replace(/,/,"")) * parseFloat($objTr.find("td").eq(9).text().replace(/,/,""));
        $objTr.find("td").eq(10).text($allPrice);
        formatMoneyThis($objTr.find("td").eq(6), 2);
        formatMoneyThis($objTr.find("td").eq(7), 2);
        formatMoneyThis($objTr.find("td").eq(8), 2);
        formatMoneyThis($objTr.find("td").eq(9), 2);
        formatMoneyThis($objTr.find("td").eq(10), 2);
        $("#listHtml tr").eq(index).find(".materialTotalPrice").val($allPrice);
        $("#listHtml tr").eq(index).find(".materialLoss").val($allConsumption);
	}
    </script>
</head>
<body>
<!-- 创建编辑头部 -->   
<div id="editPage" class="layerHeader clearfix">
<c:choose>
	   <c:when test="${bigConsumption.id!=null && bigConsumption.id!=''}">
	    <!-- 编辑 --> 
			<p class="headerTitle"><spring:message code="bigConsumption_head_edit"/></p>
       </c:when>
       <c:otherwise>
        <!-- 创建 --> 
            <p class="headerTitle"><spring:message code="bigConsumption_head_create"/></p>
       </c:otherwise>
    </c:choose>
    <div class="headerButton clearfix">
    	<button type="button" onclick="popup('1230px','620px','${ctx}/common/material/list')"><spring:message code="addMaterial"/></button>
        <button type="button" id="confirmBtn"><spring:message code="btn_ok"/></button>
        <button type="button" onclick="closeWin()"><spring:message code="btn_cancle"/></button>
    </div>
</div>
<form id="inputForm" method="post">
	<div id = "fileListHidden">
	</div>
<!-- 确认页面head部 -->
<div id="confirmPage" class="layerHeader clearfix" style="display:none">
	<p class="headerTitle"><spring:message code="bigConsumption_head_confirm"/></p>
    <div class="headerButton clearfix">
        <shiro:hasPermission name="bigcargo:consumption:edit">
        <button type="button" id="saveBtn" onclick="saveForm()"><spring:message code="common_save"/></button>
			</shiro:hasPermission>
        <button type="button" onclick="closeWin()"><spring:message code="btn_cancle"/></button>
    </div>
</div>
<div class="tabBox">
    <ul class="clearfix">
     	<li class="active"><spring:message code="bigConsumption"/></li>
        <li><spring:message code="bigConsumption_auxiliary_plane_batching"/></li>
    </ul>
</div>
<div id="showHtml" class="tabBoxSm" >
    <div class="tabSm smOrderBox">
        <div class="items clearfix">
            <div class="col-33 clearfix haveToBox">
            	<p class="tit"><spring:message code="bigConsumption_no" /></p>
            	<input type="hidden" id="styleId" name="styleId"  value="${bigConsumption.styleId}">
				<input id="styleNo" name="styleNo"  value="${bigConsumption.styleNo}" readonly="readonly" data-rule-required="true" data-msg-required="<spring:message code="please_select_style_no" />">
				<button type="button" onclick="popup('900px','584px','${ctx}/quotation/message/createStyle?frameFlg=2')">选择</button>
            	<p class="haveTo">*</p>
            </div>
            <div class="col-33 clearfix">
                <p class="tit"><spring:message code="bigConsumption_name" /></p>
				<input id="styleNameCn" name="styleNameCn" style="width: 200px;"  value="${bigConsumption.styleNameCn}" readonly= "readonly">
            </div>
        </div>
        <div class="items clearfix">
            <div class="col-33 clearfix">
            <input type="hidden" id="id" name="id"  value="${bigConsumption.id}">
            <input type="hidden" id="sampleRequestId" name="sampleRequestId"  value="${bigConsumption.sampleRequestId}">
                <p class="tit"><spring:message code="bigConsumption_refUnitCostNo" /></p>
                <c:choose>
	   			<c:when test="${bigConsumption.id!=null && bigConsumption.id!=''}">
				<input id="unitCostNo" name="unitCostNo"  value="${bigConsumption.unitCostNo}" readonly="readonly">
       			</c:when>
       			<c:otherwise>
           		<%-- <input id="unitCostNo" name="unitCostNo"  value="${bigConsumption.unitCostNo}" > --%>
           		<select id="unitCostNo" name="unitCostNo" style="width: 150px" onchange="findUnit(this);">
           			
                </select>
       			</c:otherwise>
    			</c:choose>
            </div>
        </div>
        <p class="title" style="margin-top: 20px;"><spring:message code="bigConsumption_Information" /></p>
        <div class="clearfix">
            	<div class="items clearfix">        	
                    <div class="col-33 clearfix haveToBox">
                        <p class="tit"><spring:message code="bigConsumption_head_unitCostMiddleStandard" /></p>
						<input id="unitCostMiddleStandard" name="unitCostMiddleStandard"  value="${bigConsumption.unitCostMiddleStandard}" data-rule-required="true" data-msg-required="<spring:message code="please_select_unitCostMiddleStandard" />">
                    	<p class="haveTo">*</p>
                    </div>
                    <div class="col-33 clearfix haveToBox">
                        <p class="tit"><spring:message code="bigConsumption_unitCostLossRate" /></p>   
						<input id="unitCostLossRate" name="unitCostLossRate" onchange="giveThisData();"  value="${bigConsumption.unitCostLossRate}" data-rule-required="true" data-msg-required="<spring:message code="please_select_unitCostLossRate" />">&nbsp;%
                    	<p class="haveTo">*</p>
                    </div>
					<div class="col-33 clearfix haveToBox">
                        <p class="tit"><spring:message code="bigConsumption_cost" /></p>
						<input id="unitCost" name="unitCost" value="${bigConsumption.unitCost}" data-rule-required="true" data-msg-required="<spring:message code="please_select_unitCost" />">
                    	<p class="haveTo">*</p>
                    </div>
                </div>
                <div class="items clearfix" style="margin-bottom:0;">     
                    <p class="tit"><spring:message code="bigConsumption_unitCostRemark" /></p>
					<textarea id="unitCostRemark" name="unitCostRemark" style="width:465px;height: 60px">${bigConsumption.unitCostRemark }</textarea>
                </div>
				<div class="items clearfix">
                    <div class="col-33 clearfix" style="padding:20px;padding-left:0px;">
                        <p class="tit"><spring:message code="bigConsumption_creater" /></p>
                        <%-- <p>${fns:getUser()}</p> --%>
                        <input id="createUserId" name="createUserId" value="${bigConsumption.createBy.firstName}${bigConsumption.createBy.lastName}" readonly="readonly">
                    </div>
                    <div class="col-33 clearfix" style="padding:20px;padding-left:0px;">
                        <p class="tit"><spring:message code="bigConsumption_create_date" /></p>
                        <%-- <p id="createDate" name="createDate">${fns:getDate("yyyy-MM-dd HH:mm")}</p> --%>
                        <input id="createDate" name="createDate" value="${fns:getDate('yyyy-MM-dd HH:mm')}" readonly="readonly">
                    </div>
                </div>
        </div>
	</div>
    <div class="tabSm none">
    	<div class="tableArea" >
        	<div class="tableScrollSm" style="overflow: auto;width: 888px;">
        		<table cellpadding="0" class="tableHead">
                    <thead>
                    <tr>
						<th class="tab-cz"><spring:message code="bigConsumption_operation" /></th>
                        <th class="tab-wltp"><spring:message code="bigConsumption_pic" /></th>
                        <th class="tab-wlmcbj"><spring:message code="bigConsumption_materialno_name" /></th>
                        <th class="tab-wllb"><spring:message code="bigConsumption_materialType" /></th>
                        <th class="tab-fk"><spring:message code="bigConsumption_breadth" /></th>
                        <th class="tab-dw"><spring:message code="bigConsumption_unit" /></th>
                        <th class="tabInput-dh"><spring:message code="bigConsumption_onsumption" /></th>
                        <th class="tabInput-sh"><spring:message code="bigConsumption_unitCostLossRate_no" /></th>
                        <th class="tabInput-hshdh"><spring:message code="bigConsumption_unitCostLossRate_in" /></th>
                        <th class="tabInput-ckdj"><spring:message code="bigConsumption_price" /></th>
                        <th class="tabInput-ckcb"><spring:message code="bigConsumption_cost" /></th>
                        <th class="tabInput-sysm"><spring:message code="bigConsumption_use" /></th>
                    </tr>
                    </thead>
                </table>
                <table cellpadding="0" class="tableBody">
                    <tbody id="listHtml">
					</tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</form>
<script>
	window.onload = function(){
			var windowH = window.innerHeight
					||document.documentElement.clientHeight
					||document.body.clientHeight
			$('.tabSm').css({
				'height':windowH - 77,
			});
			$('.tableScrollSm').css({
				'height':windowH - 91
			})
		}
</script>
</body>
</html>